// 获取DOM元素
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('fileInput');
const qualitySlider = document.getElementById('quality');
const qualityValue = document.getElementById('qualityValue');
const originalPreview = document.getElementById('originalPreview');
const compressedPreview = document.getElementById('compressedPreview');
const originalSize = document.getElementById('originalSize');
const compressedSize = document.getElementById('compressedSize');
const downloadBtn = document.getElementById('downloadBtn');
const compressionControls = document.getElementById('compressionControls');
const previewContainer = document.getElementById('previewContainer');
const downloadArea = document.getElementById('downloadArea');

let originalFile = null;
let compressedFile = null;
let imageFiles = []; // 存储所有待处理的图片文件
let compressedFiles = []; // 存储所有压缩后的图片文件

// 拖拽上传处理
dropZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    dropZone.classList.add('drag-over');
});

dropZone.addEventListener('dragleave', (e) => {
    e.preventDefault();
    dropZone.classList.remove('drag-over');
});

dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    dropZone.classList.remove('drag-over');
    const files = Array.from(e.dataTransfer.files);
    if (files.length > 10) {
        alert('一次最多只能上传10张图片！');
        return;
    }
    handleFiles(files);
});

// 文件选择处理
fileInput.addEventListener('change', (e) => {
    const files = Array.from(e.target.files);
    if (files.length > 10) {
        alert('一次最多只能上传10张图片！');
        return;
    }
    handleFiles(files);
});

// 添加防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 优化压缩处理函数
const debouncedCompression = debounce(async (files, quality) => {
    await compressAllImages(quality);
}, 200);

// 修改质量滑块变化处理
qualitySlider.addEventListener('input', (e) => {
    qualityValue.textContent = `${e.target.value}%`;
    if (imageFiles.length > 0) {
        debouncedCompression(imageFiles, e.target.value / 100);
    }
});

// 新增批量文件处理函数
async function handleFiles(files) {
    // 清空之前的文件
    imageFiles = [];
    compressedFiles = [];
    previewContainer.innerHTML = '';
    
    // 过滤非图片文件
    const imageFilesArray = files.filter(file => file.type.startsWith('image/'));
    if (imageFilesArray.length === 0) {
        alert('请上传图片文件！');
        return;
    }

    imageFiles = imageFilesArray;
    
    // 显示控制区域
    compressionControls.style.display = 'block';
    previewContainer.style.display = 'grid';
    document.getElementById('batchControls').style.display = 'block';
    
    // 为每个文件创建预览元素
    imageFiles.forEach((file, index) => {
        const previewBox = createPreviewBox(file, index);
        previewContainer.appendChild(previewBox);
    });
    
    // 压缩所有图片
    await compressAllImages(qualitySlider.value / 100);
}

// 修改创建预览框函数
function createPreviewBox(file, index) {
    const previewBox = document.createElement('div');
    previewBox.className = 'preview-box';
    previewBox.innerHTML = `
        <h3>图片 ${index + 1}</h3>
        <div class="image-comparison">
            <div class="image-side">
                <h4>原始图片</h4>
                <div class="image-container">
                    <img src="${URL.createObjectURL(file)}" alt="预览图片 ${index + 1}" class="original-preview">
                </div>
                <div class="file-info">
                    <span class="original-size">原始大小: ${formatFileSize(file.size)}</span>
                </div>
            </div>
            <div class="image-side">
                <h4>压缩后</h4>
                <div class="image-container">
                    <img alt="压缩预览 ${index + 1}" class="compressed-preview">
                </div>
                <div class="file-info">
                    <span class="compressed-size"></span>
                </div>
            </div>
        </div>
        <button class="download-btn single-download" data-index="${index}">下载此图片</button>
    `;
    return previewBox;
}

// 批量压缩函数
async function compressAllImages(quality) {
    try {
        compressedFiles = [];
        const compressionPromises = imageFiles.map(file => compressImage(file, quality));
        await Promise.all(compressionPromises);
    } catch (error) {
        console.error('批量压缩失败:', error);
        alert('部分图片压缩失败，请重试！');
    }
}

// 修改压缩图片函数
async function compressImage(file, quality) {
    try {
        const options = {
            maxSizeMB: 0.5,
            maxWidthOrHeight: 1600,
            useWebWorker: true,
            quality: quality,
            alwaysKeepResolution: false,
            initialQuality: quality,
            fileType: 'image/jpeg',
        };

        if (file.size > 1024 * 1024) {
            options.maxWidthOrHeight = 1200;
            options.maxSizeMB = 0.3;
        }

        let compressedFile = await imageCompression(file, options);
        
        if (compressedFile.size > 500 * 1024) {
            options.maxSizeMB = 0.2;
            options.maxWidthOrHeight = 1000;
            compressedFile = await imageCompression(compressedFile, options);
        }

        // 更新预览和大小信息
        const index = imageFiles.indexOf(file);
        const previewBox = previewContainer.children[index];
        const compressedPreview = previewBox.querySelector('.compressed-preview');
        const compressedSizeSpan = previewBox.querySelector('.compressed-size');
        
        compressedPreview.src = URL.createObjectURL(compressedFile);
        compressedSizeSpan.textContent = `压缩后大小: ${formatFileSize(compressedFile.size)}`;
        
        // 存储压缩后的文件
        compressedFiles[index] = compressedFile;
        
    } catch (error) {
        console.error('压缩失败:', error);
        throw error;
    }
}

// 添加批量下载处理
document.getElementById('downloadAllBtn').addEventListener('click', () => {
    if (compressedFiles.length === 0) return;
    
    compressedFiles.forEach((file, index) => {
        const link = document.createElement('a');
        link.href = URL.createObjectURL(file);
        link.download = `compressed_${imageFiles[index].name}`;
        link.click();
    });
});

// 添加 ZIP 打包下载处理
document.getElementById('downloadZipBtn').addEventListener('click', async () => {
    if (compressedFiles.length === 0) return;
    
    try {
        const zip = new JSZip();
        
        // 添加所有压缩后的图片到 zip
        for (let i = 0; i < compressedFiles.length; i++) {
            const file = compressedFiles[i];
            const fileName = `compressed_${imageFiles[i].name}`;
            zip.file(fileName, file);
        }
        
        // 生成 zip 文件
        const content = await zip.generateAsync({
            type: 'blob',
            compression: 'DEFLATE',
            compressionOptions: {
                level: 9
            }
        });
        
        // 下载 zip 文件
        const link = document.createElement('a');
        link.href = URL.createObjectURL(content);
        link.download = 'compressed_images.zip';
        link.click();
    } catch (error) {
        console.error('ZIP 打包失败:', error);
        alert('ZIP 打包失败，请重试！');
    }
});

// 新增批量文件处理函数
async function handleFiles(files) {
    // 清空之前的文件
    imageFiles = [];
    compressedFiles = [];
    previewContainer.innerHTML = '';
    
    // 过滤非图片文件
    const imageFilesArray = files.filter(file => file.type.startsWith('image/'));
    if (imageFilesArray.length === 0) {
        alert('请上传图片文件！');
        return;
    }

    imageFiles = imageFilesArray;
    
    // 显示控制区域
    compressionControls.style.display = 'block';
    previewContainer.style.display = 'grid';
    document.getElementById('batchControls').style.display = 'block';
    
    // 为每个文件创建预览元素
    imageFiles.forEach((file, index) => {
        const previewBox = createPreviewBox(file, index);
        previewContainer.appendChild(previewBox);
    });
    
    // 压缩所有图片
    await compressAllImages(qualitySlider.value / 100);
}

// 文件大小格式化
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 添加单张图片下载处理
previewContainer.addEventListener('click', (e) => {
    if (e.target.classList.contains('single-download')) {
        const index = parseInt(e.target.dataset.index);
        if (compressedFiles[index]) {
            const link = document.createElement('a');
            link.href = URL.createObjectURL(compressedFiles[index]);
            link.download = `compressed_${imageFiles[index].name}`;
            link.click();
        }
    }
}); 